package com.zwh.modules.goods.rabbitmq;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.amqp.core.DirectExchange;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSONObject;
import com.zwh.autoconfigure.rabbitmq.DirectExchangeConfig;
import com.zwh.modules.goods.entity.Goods;
import com.zwh.modules.goods.service.GoodsService;
import com.zwh.modules.order.entity.Order;

/**
 * @author monkey
 * @date 2020/11/6 15:17
 **/
@Service
public class MessageReceiver {

    private static Logger log = LoggerFactory.getLogger(MessageReceiver.class);

    @Autowired
    GoodsService goodsService;

    /**
     * 客户秒杀商品 消费者
     * @param message
     */
    @RabbitListener(queues= DirectExchangeConfig.SECONDKILL_QUEUE)
    public void receive(String message) {
        log.info("receive message:"+message);
        //String 转换成Bean对象
        UserBuyGoodsMessage userBuyGoodsMessage  = JSONObject.parseObject(message, UserBuyGoodsMessage.class);
        String goodsId = userBuyGoodsMessage.getGoodsId();
        // TODO 判断消息重复消费处理

        //判断是否已经秒杀到了
        // 是否已经下单
        Order order = goodsService.getByUserIdWithGoodsId(userBuyGoodsMessage.getUserId(), goodsId);
        if(order != null) {
            return;
        }
        //通过商品id查询秒杀商品
        Goods goods = goodsService.getById(goodsId);

        // TODO 如果是多消费者情况下，需要使用update stock_sum=stock_sum -1 where stock_sum-1>=0 来保证原子性操作。
        //判断库存是否足够
        int stock = goods.getStockSum();
        if(stock <= 0) {
            return;
        }
        //减库存 下订单 写入秒杀订单
        goodsService.realDoBuyGoods(userBuyGoodsMessage.getUserId(), goods);
    }
}
